using System.Data;
using WebSMS.Core.ResponseEntity;

namespace WebSMS;

[Route("[controller]/[action]")]
[Controller]
//[Authorize]
public class MenuController : ControllerBase
{
    private readonly ITerMenu _menuService;
    public MenuController(MenuService menuService)
    {
        _menuService = menuService;
    }

    [HttpGet]
    [Authorize]
    public async Task<ResponseObject<List<MenuCollection>>> GetMenuList()
    {
        var token = HttpContext.Request.Headers["Authorization"].ToString();
        if (token.Equals("") || string.IsNullOrEmpty(token))
        {
            return new ResponseObject<List<MenuCollection>>().Fail("身份验证失败,请重新登录!");
        }
        string[] strings = token.Split("  ");
        var jwtToken = JWTEncryption.ReadJwtToken(strings[1]);
        var userId = jwtToken.GetClaim("UserId").Value;
        var ruleList = jwtToken.GetPayloadValue<List<UserRuleLinks>>("Rules");

        List<MenuCollection> list = await _menuService.GetMenuList(userId,ruleList);
        return new ResponseObject<List<MenuCollection>>().Ok(list,"查找成功");
    }

    [HttpPost]
    public async Task<ResponseObject<MenuPo>> AddMenu([FromBody] MenuForm menu)
    {
        await _menuService.AddMenu(new MenuPo()
        {
            Icon = menu.Icon,
            Name = menu.Name,
            ParentMenu = menu.ParentMenu,
            Path = menu.Path,
            Priority = menu.Priority,
            Id =  Guid.NewGuid()
        });
        return new ResponseObject<MenuPo>().Ok("添加成功");
    }

    [HttpPut]
    public async Task<ResponseObject<MenuPo>> UpdateMenu([FromBody] MenuPo menu)
    {
       await _menuService.UpdateMenu(menu);
       return new ResponseObject<MenuPo>().Ok("修改成功");
    }

    [HttpDelete]
    public async Task<ResponseObject<bool>> DeleteMenu(Guid menuId)
    {
        bool result = await _menuService.DeleteMenu(menuId);
        if (result)
        {
            return new ResponseObject<bool>().Ok("删除成功");
        }
        return new ResponseObject<bool>().Fail("该菜单存在子菜单或已绑定用户，请先解绑或删除子菜单");
    }
}